from common import ArtistEntity,SearchFilter
import DatabaseConnection

class ArtistData(object):
    def __init__(self):
        pass

    def InsertArtist(self,artist):
        ID = None
        
        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.callproc('InsArtist',(artist.Name,artist.BirthDate))
##        ID = cursor.lastrowid
        ID = cursor.fetchone()[0]
        cursor.close()
        conn.commit()
        conn.close()

        return ID

    def UpdateArtist(self,artist):
        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.callproc('UpdArtist',(artist.ArtistID,artist.Name,artist.BirthDate))
        cursor.close()
        conn.commit()
        conn.close()

    def DeleteArtist(self,ID):
        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.callproc('DelArtist',(ID,))
        cursor.close()
        conn.commit()
        conn.close()

    #This method either return an object of type ArtistEntity or None (if there is no record with this ID)
    def SelectArtistByID(self,ID):
        query = """ SELECT ArtistID,Name,BirthDate
                    FROM vwArtist
                    WHERE Username='%s'""" % ID

        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
                
        if len(result) <> 0:
            return ArtistEntity.ArtistEntity(artistID=result[0][0],name=result[0][1],birthDate=result[0][2])
        else:
            return None

    #This method returns a list of objects of type ArtistEntity
    def SelectArtistByFilter(self,searchFilter):
        query = """ SELECT ArtistID,Name,BirthDate
                    FROM vwArtist"""

        whereClause = searchFilter.GetWhereClause()
        if whereClause.strip()<>"":
            query += " WHERE %s" % whereClause

        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
                
        recordSet = []
        for record in result:
            recordSet.append(ArtistEntity.ArtistEntity(artistID=record[0],name=record[1],birthDate=record[2]))
        return recordSet

    #This method returns a list of objects of type ArtistEntity
    def SelectAllArtists(self):
        query = """ SELECT ArtistID,Name,BirthDate
                    FROM vwArtist"""

        conn = DatabaseConnection.GetConnection()

        cursor = conn.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
                
        recordSet = []
        for record in result:
            recordSet.append(ArtistEntity.ArtistEntity(artistID=record[0],name=record[1],birthDate=record[2]))
        return recordSet
